package com.feib.soeasy.action;

import java.util.ArrayList;

import com.feib.soeasy.model.FormatDefinition;
import com.feib.soeasy.model.Group;
import com.feib.soeasy.model.Payment;
import com.feib.soeasy.model.UploadFile;
import com.feib.soeasy.pagination.ItemGroupListBean;
import com.feib.soeasy.pagination.PaginatedList;
import com.feib.soeasy.service.AsyncService;
import com.feib.soeasy.service.PaymentItemService;
import com.feib.soeasy.service.PaymentService;
import com.feib.soeasy.service.UploadFileService;
import com.feib.soeasy.util.UserUtil;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontBind;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.ValidationErrorHandler;
import net.sourceforge.stripes.validation.ValidationErrors;


/**
 * @title (#)Soez2003ActionBean.java <br>
 * @description 帳單整批上傳放行 Controller<br>
 * @author Leo Lee
 * @version 1.0.0 2010/11/24
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2010/11/24 create by Leo Lee<br>
 */
public class Soez2003ActionBean extends BaseActionBean implements ValidationErrorHandler {

    /**
     * 帳單整批上傳放行畫面
     */
    private static final String DEFAULT_JSP = "/WEB-INF/views/soez2003/soez2003.jsp";

    /**
     * 帳單整批上傳放行清單畫面
     */
    private static final String UPLOAD_LIST_JSP = "/WEB-INF/views/soez2003/soez2003List.jsp";

    /**
     * 帳單放行畫面
     */
    private static final String PAYMENTS_GROUP_JSP = "/WEB-INF/views/soez2003/soez2003Group.jsp";

    /**
     * 帳單放行結果畫面
     */
    private static final String AFTER_CONFIRM_JSP = "/WEB-INF/views/soez2003/afterConfirm.jsp";

    /**
     * 檔案內容
     */
    private static final String AJAX_QUERY_PAYMENT_JSP = "/WEB-INF/views/soez2003/paymentList.jsp";

    /**
     * 查詢結果
     */
    private PaginatedList<UploadFile> queryResult;


    /**
     * 檔案帳單明細查詢結果
     */
    private PaginatedList<ItemGroupListBean> queryPaymentItemResult;

    /**
     * 應繳總金額
     */
    private Long totalPaymentAmount;

    /**
     * 應繳總筆數
     */
    private Long countPayemntItem;
    /**
     * 應繳檔案名稱
     */
    private String fileName;

    /**
     * 檔案放行結果
     */
    private String confirmMessage;

    /**
     * 檔案帳單明細查詢結果
     */
    private PaginatedList<Payment> queryPaymentResult;
    
    private ArrayList<UploadFile> checkUploadFiles;

    @SpringBean("uploadFileService")
    private UploadFileService uploadFileService;

    @SpringBean("paymentService")
    private PaymentService paymentService;

    @SpringBean("paymentItemService")
    private PaymentItemService paymentItemService;

    @SpringBean("asyncService")
    private AsyncService asyncService;

    private UploadFile qryUploadFile;

    @DontBind
    @DefaultHandler
    public Resolution doDefault()
    {
        logger.debug("Enter doDefault mehtod.");
        return new ForwardResolution(DEFAULT_JSP); 
    }
    
    /**
     * 批次確認帳單放行/刪除審核
     */
    public Resolution doAjaxBatchUploadFileConfirm()
    {
    	logger.debug("Enter doAjaxBatchUploadFileConfirm mehtod.");
        try {
            if(checkUploadFiles != null && checkUploadFiles.size() > 0)
            {
	            asyncService.doBatchCreateReport(checkUploadFiles, UserUtil.getUser());
	            
	            paymentService.batchUpdatePaymentStatusByUploadFile(
	            		checkUploadFiles, UserUtil.getUser() , qryUploadFile.getFileStatus());
	
	            if (qryUploadFile.getFileStatus().equals(UploadFile.FILE_STATUS_CREATE_REPORT))
	                confirmMessage = "檔案已放行，「請繼續執行列印作業」。";
	            else
	                confirmMessage = "檔案已刪除！";
            }
        } catch (Exception e) {
            confirmMessage = "處理失敗！";
            logger.error(e.toString(), e);
        }
        return new ForwardResolution(AFTER_CONFIRM_JSP);
    }

    /**
     * 查詢待放行清單
     * @return
     */
    public Resolution doAjaxQuery()
    {
        logger.debug("Enter doAjaxQuery mehtod.");
        try {
            if (null == qryUploadFile)
                qryUploadFile = new UploadFile();

            // 查上傳人員與目前使用者同一個Group 的案件
            Group group = new Group();
            group.setGroupPk(UserUtil.getUserGroup().getGroupPk());
            qryUploadFile.setGroup(group);
            
            //轉入類別 繳費單資料
            FormatDefinition formatDefinition = new FormatDefinition();
            formatDefinition.setFormatType(new Integer(1));
            qryUploadFile.setFormatDefinition(formatDefinition);
            
            if (null == queryResult)
                queryResult = new PaginatedList<UploadFile>();
            queryResult.setPageSize(1000);
            //呼叫服務查詢
            queryResult.setPaginatedList(uploadFileService.queryUnConfirmByUploadFile(qryUploadFile));

        }catch (Exception e) {
            logger.error("查詢待放行清單錯誤(Soez2003ActionBean.doAjaxQuery):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doDefulat.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }
        return new ForwardResolution(UPLOAD_LIST_JSP);
    }


    /**
     * 帳單放行審核
     * fileStatus : 4: 確認放行, 5: 不放行(表上傳資料有誤)
     * isConfirmStatus : True: 放行 False: 不放行
     * confirmDate : 放行日期
     * @return
     */
    public Resolution doAjaxPaymentsConfirm()
    {
        logger.debug("Enter doAjaxPaymentsConfirm mehtod.");
        try {
            if (null == qryUploadFile)
                qryUploadFile = new UploadFile();

            if(qryUploadFile.getFileStatus() != null  &&
            		qryUploadFile.getFileStatus().intValue() != UploadFile.FILE_STATUS_CONFIRM_NOT_OK)
            	asyncService.doCreateReport(qryUploadFile.getUploadFilePk(), UserUtil.getUser());        
            
            logger.debug("qryUploadFile.getUploadFileP {}",qryUploadFile.getUploadFilePk());
            logger.debug("qryUploadFile.getFileStatus {}",qryUploadFile.getFileStatus());
            
            /* 
             * 更新payment 狀態,
             * 放行移至create report job
             * 不放行直接刪除payment , 更新fileStatus
             */
            paymentService.updatePaymentStatusByUploadFile(qryUploadFile);

            if (qryUploadFile.getFileStatus().equals(UploadFile.FILE_STATUS_CREATE_REPORT))
                confirmMessage = "檔案已放行，產生繳費單中...";
            else
                confirmMessage = "檔案已刪除！";

        } catch (Exception e) {
            confirmMessage = "處理失敗！";
            logger.error(e.toString(), e);
        }
        return new ForwardResolution(AFTER_CONFIRM_JSP);
    }


    /**
     * 顯示明細
     * @return
     */
    public Resolution doAjaxQueryPayments()
    {
        logger.debug("Enter doAjaxQueryPayments mehtod.");
        if (null == qryUploadFile)
            qryUploadFile = new UploadFile();


        setTotalPaymentAmount(
                        paymentService.getTotalAmountByUploadFilePk(
                                        qryUploadFile.getUploadFilePk()));

        setCountPayemntItem(paymentService.getCountItemByUploadFilePk(
                        qryUploadFile.getUploadFilePk()));

        UploadFile uploadFile = uploadFileService.getUploadFileByPk(qryUploadFile.getUploadFilePk());
        if(null != uploadFile)
            setFileName(uploadFile.getFileName());

        setQueryPaymentItemResult(
                        paymentItemService.queryPaymentItemGroupByUploadFilePk(
                                        qryUploadFile.getUploadFilePk()));

        return new ForwardResolution(PAYMENTS_GROUP_JSP);
    }

    /**
     * 查詢轉入的帳單資料
     * @return
     */
    public Resolution doAjaxQueryFilePayments()
    {
        logger.debug("Enter doAjaxQueryFilePayments mehtod.");
        try {
            //如果不是銀行端，則查詢條件要加入帳單業者限制
            //            if (!UserUtil.isBankGroup())
            //            {
            Group group = new Group();
            group.setGroupPk(UserUtil.getUserGroup().getGroupPk());
            qryUploadFile.setGroup(group);
            //            }

            // 設定查詢條件
            Payment payment = new Payment();
            //payment.setGroup(qryUploadFile.getUploadGroup());
            UploadFile uploadFile = new UploadFile();
            uploadFile.setUploadFilePk(qryUploadFile.getUploadFilePk());
            payment.setUploadFile(uploadFile);
            //呼叫服務查詢
            queryPaymentResult = paymentService.queryByPayment(payment, null, null, queryPaymentResult);

        }
        catch (Exception e) {
            logger.error("上傳記錄查詢-帳單內容查詢錯誤(Soez2003ActionBean.doAjaxQueryFilePayments):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doAjaxQuery.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }

        return new ForwardResolution(AJAX_QUERY_PAYMENT_JSP);
    }


    public UploadFile getQryUploadFile() {
        return qryUploadFile;
    }

    public void setQryUploadFile(UploadFile qryUploadFile) {
        this.qryUploadFile = qryUploadFile;
    }

    /**
     * @return the queryResult
     */
    public PaginatedList<UploadFile> getQueryResult() {
        return queryResult;
    }


    /**
     * @param queryResult the queryResult to set
     */
    public void setQueryResult(PaginatedList<UploadFile> queryResult) {
        this.queryResult = queryResult;
    }


    public Long getTotalPaymentAmount() {
        return totalPaymentAmount;
    }

    public void setTotalPaymentAmount(Long totalPaymentAmount) {
        this.totalPaymentAmount = totalPaymentAmount;
    }

    public Long getCountPayemntItem() {
        return countPayemntItem;
    }

    public void setCountPayemntItem(Long countPayemntItem) {
        this.countPayemntItem = countPayemntItem;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public PaginatedList<ItemGroupListBean> getQueryPaymentItemResult() {
        return queryPaymentItemResult;
    }

    public void setQueryPaymentItemResult(
                    PaginatedList<ItemGroupListBean> queryPaymentItemResult) {
        this.queryPaymentItemResult = queryPaymentItemResult;
    }


    /**
     * @return the confirmMessage
     */
    public String getConfirmMessage() {
        return confirmMessage;
    }


    /**
     * @param confirmMessage the confirmMessage to set
     */
    public void setConfirmMessage(String confirmMessage) {
        this.confirmMessage = confirmMessage;
    }

    public PaginatedList<Payment> getQueryPaymentResult() {
        return queryPaymentResult;
    }

    public void setQueryPaymentResult(PaginatedList<Payment> queryPaymentResult) {
        this.queryPaymentResult = queryPaymentResult;
    }

	public ArrayList<UploadFile> getCheckUploadFiles() {
		return checkUploadFiles;
	}

	public void setCheckUploadFiles(ArrayList<UploadFile> checkUploadFiles) {
		this.checkUploadFiles = checkUploadFiles;
	}


}
